import { Controller } from 'egg';
import { saveImg } from '../utils/common/dealImg';
import { RESULT_CODE } from '../utils/constants/code';
export default class RestaurantController extends Controller {
  /**
   * 添加美食店申请
   */
  async addRestaurant() {
    const { ctx } = this;

    // 参数验证
    const rule = {
      name: { type: 'string', required: true, message: '店名不能为空' },
      address: { type: 'string', required: true, message: '地址不能为空' },
      description: { type: 'string', required: false },
      tags: { type: 'string', required: false },
    };

    ctx.validate(rule, ctx.request.body);

    try {
      const files = ctx.request.files;
      const data = Date.now(); // 毫秒数
      const ps:any = [];
      files && files.forEach((it:any, index:number) => {
        ps.push(saveImg({
          file: it,
          targetPath: this.config.uploadPathMap.uploadComRestaurantsDir,
          ctx,
          fileName: data + index,
          isAutoClear: false,
        }));
      });
      const retPaths = await Promise.all(ps);
      const pictures = retPaths?.map(it => it).join(',');
      ctx.cleanupRequestFiles();


      const result = await ctx.service.restaurant.addRestaurant({ ...ctx.request.body, pictures });
      
      ctx.body = {
        code: 200,
        message: '申请提交成功，等待审核',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }
  /**更新美食店信息 */
  async updateRestaurant() {
    const { ctx } = this;
    // 参数验证
    const rule = {
      name: { type: 'string', required: true, message: '店名不能为空' },
      address: { type: 'string', required: true, message: '地址不能为空' },
      description: { type: 'string', required: false },
      tags: { type: 'string', required: false },
    };

    ctx.validate(rule, ctx.request.body);
    const { id } = ctx.request.body;
    let pictures = '';
    try {
      const files = ctx.request.files;
      if(files && files.length > 0) {
        const data = Date.now(); // 毫秒数
        const ps:any = [];
        files && files.forEach((it:any, index:number) => {
          ps.push(saveImg({
            file: it,
            targetPath: this.config.uploadPathMap.uploadComRestaurantsDir,
            ctx,
            fileName: data + index,
            isAutoClear: false,
          }));
        });
        const retPaths = await Promise.all(ps);
        pictures = retPaths?.map(it => it).join(',');
        ctx.cleanupRequestFiles();
      }
      const result = await ctx.service.restaurant.updateRestaurant(parseInt(id), { ...ctx.request.body, pictures });
      
      ctx.body = {
        code: 200,
        message: '更新成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  /**更新美食店基础信息 */
  async updateRestaurantBaseInfo() {
    const { ctx } = this;
    // 参数验证
    const rule = {
      address: { type: 'string', required: true, message: '地址不能为空' },
      description: { type: 'string', required: false },
      tags: { type: 'string', required: false },
    };

    ctx.validate(rule, ctx.request.body);
    const { id } = ctx.request.body;
    const { address, phone, per_price, open_time, description, tags, province_id, city_id, area_id } = ctx.request.body;
    const data = { address, phone, per_price, open_time, description, tags, province_id, city_id, area_id };
    try {
      const result = await ctx.service.restaurant.updateRestaurant(parseInt(id), data);
      
      ctx.body = {
        code: 200,
        message: '更新成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }
  
  /**
   * 获取美食店列表
   */
  async getRestaurantList() {
    const { ctx } = this;

    try {
      const result = await ctx.service.restaurant.getRestaurantList(ctx.query);
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  /**
   * 获取美食店详情
   */
  async getRestaurantDetail() {
    const { ctx } = this;
    const { id } = ctx.query;
    console.log('config.host', this.config.host);
    try {
      const result = await ctx.service.restaurant.getRestaurantDetail(parseInt(id));
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  /**
   * 收藏/取消收藏美食店
   */
  async toggleFavorite() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      const result = await ctx.service.restaurant.toggleFavorite(parseInt(id));
      
      ctx.body = {
        code: 200,
        message: result.message,
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // 获取用户申请列表
  async getMyApplicationList() {
    const { ctx } = this;
    const { user_id } = ctx.state.user;
    try {
      const result = await ctx.service.restaurant.getApplicationList({ ...ctx.query, user_id });
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  /**
   * 管理员获取申请列表
   */
  async getApplicationList() {
    const { ctx } = this;

    // 检查管理员权限
    if (!ctx.state.user.is_admin) {
      ctx.throw(403, '权限不足');
    }

    try {
      const result = await ctx.service.restaurant.getApplicationList(ctx.query);
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  /**
   * 管理员审核美食店
   */
  async auditRestaurant() {
    const { ctx } = this;

    // 检查管理员权限
    if (!ctx.state.user.is_admin) {
      ctx.throw(403, '权限不足');
    }

    // 参数验证
    const rule = {
      status: { type: 'enum', values: ['approved', 'rejected'], message: '状态值不正确' },
      audit_remark: { type: 'string', required: false },
    };

    ctx.validate(rule);

    const { id, status, audit_remark } = ctx.request.body;

    try {
      const result = await ctx.service.restaurant.auditRestaurant(parseInt(id), status, audit_remark);
      
      ctx.body = {
        code: 200,
        message: result.message,
        data: null,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }
}